﻿using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace Database
{
    public class GioHang : DataTable
    {
        public static string Chuoi_lien_ket = ConfigurationManager.ConnectionStrings["maytinhxachtayConnectionString"].ConnectionString;
            //@"Data Source=.\sqlexpress;Initial Catalog=maytinhxachtay;Integrated Security=SSPI;";
        private string tenBang;
        private string strCon;
        private SqlDataAdapter mBo_doc_ghi;
        private static SqlConnection mKet_noi;

        public GioHang(string table, string strSQL)
            : base(table)
        {
            tenBang = table;
            strCon = strSQL;
            Doc_bang();
        }


        public static DataTable Gio_Hang()
        {
            DataTable bang = new DataTable();
            bang.Columns.Add("ma", typeof(int));
            bang.Columns.Add("ten", typeof(string));
            bang.Columns.Add("soluong", typeof(int));
            bang.Columns.Add("giaban", typeof(double));
            bang.Columns.Add("hinhanh", typeof(string));
            bang.Columns.Add("thanhtien", typeof(double), "soluong*giaban");
            return bang;
        }

        private void Doc_bang()
        {

            if (string.IsNullOrEmpty(strCon))
                strCon = "SELECT * FROM " + tenBang;

            if (mKet_noi == null)
            {
                mKet_noi = new SqlConnection();
                mKet_noi.ConnectionString = Chuoi_lien_ket;
            }

            try
            {
                //DataTable dt = (DataTable)GioHang.Gio_Hang();
                mBo_doc_ghi = new SqlDataAdapter(strCon, mKet_noi);
                this.mBo_doc_ghi.RowUpdated += new SqlRowUpdatedEventHandler(mBo_doc_ghi_RowUpdated);
                mBo_doc_ghi.Fill(this);
                mBo_doc_ghi.FillSchema(this, SchemaType.Mapped);



                mBo_doc_ghi.SelectCommand.CommandText = "select * FROM " + tenBang;
                SqlCommandBuilder Bo_phat_sinh = new SqlCommandBuilder(mBo_doc_ghi);
            }
            catch (SqlException ex)
            {
                string str = ex.Message;
            }
        }

        private void mBo_doc_ghi_RowUpdated(object sender, SqlRowUpdatedEventArgs e)
        {
            if (this.PrimaryKey[0].AutoIncrement)
            {
                if (e.Status == UpdateStatus.Continue && e.StatementType == StatementType.Insert)
                {
                    //Lay gia tri AutoNumber
                    this.PrimaryKey[0].ReadOnly = false;
                    SqlCommand cmd = new SqlCommand("Select @@IDENTITY", mKet_noi);
                    e.Row[0] = cmd.ExecuteScalar();
                    e.Row.AcceptChanges();
                }
            }
        }
    }
}
